package org.dfl.core.data.connectors;

import org.dfl.core.data.types.CollectionType;
import org.dfl.core.data.types.MapType;
import org.dfl.core.data.types.Type;
import org.dfl.core.data.types.TypeContainer;
import org.dfl.core.data.types.TypeManager;

/**
 * Type connector for collection of maps
 * @author Piotr Wlodarczyk
 *
 */
public class CollectionMapTypeConnector extends SimpleTypeConnector {
	private String subkey;
	
	/**
	 * Create a collection-map connector 
	 * @param source - any type container
	 * @param target - type container with a collection of a map subtype
	 * @param subkey - subkey in a map in target type
	 */
	public CollectionMapTypeConnector(TypeContainer source, TypeContainer target, String subkey) {
		super(source, target);
		this.subkey = subkey;
	}

	public TypeContainer getTarget() {
		Type targetType = super.getTarget().getType();
		if(TypeManager.isAnyType(targetType)){
			MapType m = TypeManager.getMapType();
			m.addSubkey(subkey, TypeManager.getAnyType());
			targetType.merge(TypeManager.getCollectionType(m));
		}else if(
			((MapType) ((CollectionType) super.getTarget().getType()).getSubtypeContainer().getType()).getSubtype(subkey)==null){			
			((MapType) ((CollectionType) super.getTarget().getType()).getSubtypeContainer().getType()).addSubkey(subkey, TypeManager.getAnyType());
		}
		// tu juz MUSI BYC ok
		return ((MapType) ((CollectionType) super.getTarget().getType()).getSubtypeContainer().getType()).getSubtype(subkey);
	}

}
